﻿using System;
using System.IO;
using System.Net.Mail;
using System.Text;

namespace OF.Utility.Email
{
    public class UseNetMail : ISendMail
    {
        private MailMessage Mail { get; set; }
        private SmtpClient Host { get; set; }

        public void CreateHost(ConfigHost host)
        {
            Host = new SmtpClient(host.Server, host.Port);
            Host.Credentials = new System.Net.NetworkCredential(host.Username, host.Password);
            Host.EnableSsl = host.EnableSsl;
        }

        public void CreateMail(ConfigMail mail)
        {
            Mail = new MailMessage();
            Mail.From = new MailAddress(mail.From);

            foreach (var t in mail.To)
                Mail.To.Add(t);

            Mail.Subject = mail.Subject;
            Mail.Body = mail.Body;
            Mail.IsBodyHtml = true;
            Mail.BodyEncoding = System.Text.Encoding.UTF8;
        }

        public void CreateMultiMail(ConfigMail mail)
        {
            CreateMail(mail);
            
            var html = AlternateView.CreateAlternateViewFromString(mail.Body, Encoding.UTF8, "text/html");
            if (mail.Resources != null)
            {
                foreach (string resource in mail.Resources)
                {
                    var image = new LinkedResource(resource, "image/jpeg");
                    image.ContentId = Convert.ToBase64String(Encoding.Default.GetBytes(Path.GetFileName(resource)));
                    html.LinkedResources.Add(image);
                }
            }
            Mail.AlternateViews.Add(html);

            foreach (var attachment in mail.Attachments)
            {
                Mail.Attachments.Add(new Attachment(attachment));
            }
        }

        public void SendMail()
        {
            if (Host != null && Mail != null)
                Host.Send(Mail);
            else
                throw new Exception("These is not a host to send mail or there is not a mail need to be sent.");
        }
    }
}
